package com.ophiux.cs.application.consultBase.impl;

import com.ophiux.cs.application.consultBase.dto.*;
import com.ophiux.cs.application.consultBase.service.IAddHospitalAppService;
import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.domain.consultBase.domainservice.HospitalDomainService;
import com.ophiux.cs.domain.consultBase.model.entity.Hospital;
import com.ophiux.cs.domain.consultBase.repositories.IHospitalRepository;
import com.ophiux.utils.common.RandomUtil;
import com.ophiux.utils.common.ShiftUtils;
import com.ophiux.utils.exception.OphiuxRepositoryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AddHospitalAppService implements IAddHospitalAppService {

    @Autowired
    IHospitalRepository hospitalRepositories;
    @Autowired
    HospitalDomainService hospitalDomainService;

    @Override
    public Result<AddHospitalResponse> createHospital(AddHospitalRequest dto) {
        AddHospitalResponse resp = new AddHospitalResponse();
        //验证参数是否允许为空
        if (!dto.isParamValid()) {
            return Result.fail(ResultEnum.requestParamFail.getCode(), ResultEnum.requestParamFail.getMsg());
        }
        try {
            Hospital hos = null;
            hos = (Hospital) ShiftUtils.objToNewObj(dto, Hospital.class);
//            hospitalDomainService.createHospital(hos);
            boolean flag=true;
            String hosID="";
            //生成科室分类编码
            while(flag){
                //随机生成6位数
                hosID= RandomUtil.getRandomNum(6);
                Hospital h=hospitalRepositories.getHospitalByHosID(hosID);
                if(h==null){
                    hos.setHOSPITAL_ID("H"+hosID);
                    flag=false;
                }
            }
            try {
                hospitalRepositories.createHospital(hos);
                resp.setHOSPITAL_ID(hos.getHOSPITAL_ID());
            } catch (OphiuxRepositoryException e) {
                e.printStackTrace();
                return Result.fail(ResultEnum.requestException.getCode(), e.getExceptionMessage());
            }
        } catch (Exception e) {
            log.info("createHospital接口异常：", e);
            e.printStackTrace();
            return Result.fail(AppResultCode.EXCEPTION, "程序异常");
        }
        return Result.success(resp, "新增医院成功");
    }

}
